package com.solairen.myapplication.camera;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.solairen.myapplication.R;
import com.solairen.myapplication.SelfEvaluateActivity;
import com.solairen.myapplication.utils.ApiResponseCallback;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PhotoActivity extends AppCompatActivity implements View.OnClickListener {

    private Button takePhoto, upload;
    private Button pickPhoto;
//    private TextView text;
    private ImageView image;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    private String imagePath;

    // private ActivityResultLauncher<Intent> pickImageLauncher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
//        text = findViewById(R.id.text);
        image = findViewById(R.id.image);
        pickPhoto = findViewById(R.id.pickPhoto);
        takePhoto = findViewById(R.id.takePhoto);
        upload = findViewById(R.id.upload);
        takePhoto.setOnClickListener(this);
        pickPhoto.setOnClickListener(this);
        upload.setOnClickListener(this);

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result != null) {
                Intent data = result.getData();
                if (data != null && result.getResultCode() == Activity.RESULT_OK) {
                    Log.d("upload", "开始上传");
                    this.imagePath = data.getStringExtra("path");
//                    text.setText(imagePath);
                    Bitmap bitmap = BitmapFactory.decodeFile(data.getStringExtra("path"));
                    image.setImageBitmap(bitmap);
                }
            }
        });

        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                Log.d("PhotoPicker", "Selected URI: " + uri);
                this.imagePath = copyImageToPrivateDirectory(uri);
//                text.setText(imagePath);
                image.setImageURI(uri);
            } else {
                Log.d("PhotoPicker", "No media selected");
            }
        });



/*        pickImageLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        // Handle the result of picking an image
                        Intent data = result.getData();
                        if (data != null) {
                            // Get the image URI from the result
                            Uri imageUri = data.getData();
                            // Process the imageUri as needed
                            image.setImageURI(imageUri);
                        }
                    }
                });

 */
    }

    @Override
    public void onClick(View v) {
        if (v == takePhoto) {
            Intent intent = new Intent(this, CameraActivity.class);
            intentActivityResultLauncher.launch(intent);
        }
        if (v == upload) {
            if(imagePath != null){
                sendImageFile(imagePath);
                Intent intent = new Intent(this, SelfEvaluateActivity.class);
                intentActivityResultLauncher.launch(intent);
            }else {
                Toast.makeText(this, "未选定图片", Toast.LENGTH_SHORT).show();
            }

        }

        if (v == pickPhoto) {

            pickMedia.launch(new PickVisualMediaRequest.Builder()
                    .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                    .build());


         /*   Intent pickImageIntent = new Intent(Intent.ACTION_PICK);
            pickImageIntent.setType("image/*");
            // Set the initial directory to Environment.DIRECTORY_PICTURES
            pickImageIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.fromFile(getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
            pickImageLauncher.launch(pickImageIntent);

          */
        }
    }

    private void sendImageFile(String filePath) {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("multipart/from-data");
        File imageFile = new File(filePath);
        if (imageFile.exists() && imageFile.canRead()) {
            Log.e("UploadImage", "好耶！找到了");
        } else {
            Log.e("UploadImage", "图像文件不存在或不可读");
        }
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", imageFile.getName(), RequestBody.create(mediaType, imageFile))
                .build();

        String token = getSharedPreferences("MyPreferences", MODE_PRIVATE).getString("user_token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsiaWQiOjUsInVzZXJuYW1lIjoiMTMyNDEyMzQxMjM0In0sImV4cCI6MTcxMDYyMzE1Mn0.97tXN4329yupuPrjVgOdaEszLXyE-kh5Z-2RvLcRVfY");


        Request request = new Request.Builder()
                .url("http://10.216.245.5:5000/upload")
                .post(requestBody)
                .addHeader("Authorization", token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理上传失败的情况
                Log.d("upload", "上传失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 处理上传成功的情况
                    Log.d("Upload", "Image uploaded successfully");
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        String result = jsonObject.getString("analysis_result");
                        saveResult(result);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                } else {
                    // 处理上传失败的情况
                    Log.d("Upload", "Image upload failed: " + response.message());
                }
            }
        });
    }

    private void saveResult(String result) {
        // 这里根据你的需求存储Token，例如SharedPreferences
        SharedPreferences.Editor editor = getSharedPreferences("MyPreferences", MODE_PRIVATE).edit();
        editor.putString("analysis_result", result);
        editor.apply();
    }

    private String copyImageToPrivateDirectory(Uri imageUri) {
        // 获取 ContentResolver
        ContentResolver contentResolver = getContentResolver();

        // 使用 ContentResolver 获取图片的实际路径
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = contentResolver.query(imageUri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            String imagePath = cursor.getString(columnIndex);
            cursor.close();

            // 创建要保存到私有目录的文件
            File privateDir = getFilesDir(); // 或者使用 getExternalFilesDir() 获取外部私有目录
            String timeStamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault()).format(System.currentTimeMillis());
            String fileName = "JPEG_" + timeStamp + "_";
            File destinationFile = new File(privateDir, fileName + ".jpg");

            // 将图片复制到私有目录
            try (InputStream in = Files.newInputStream(new File(imagePath).toPath());
                 OutputStream out = Files.newOutputStream(destinationFile.toPath())) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                Toast.makeText(this, "图片保存成功", Toast.LENGTH_SHORT).show();

                // 返回保存到私有目录后的文件地址字符串
                return destinationFile.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "图片保存失败", Toast.LENGTH_SHORT).show();
            }
        }

        // 如果无法获取图片的实际路径或保存失败，则返回空字符串
        return "";
    }



}